package com.sdcqjy.property.utils;

import android.support.annotation.Nullable;
import android.widget.TextView;

import com.sdcqjy.property.R;

import java.util.Date;

/**
 * Created by 磁磁帅 on 2017/7/20.
 * 描述：验证码定时器
 */
public class SmsCodeUtils {
    public SmsCodeUtils(@Nullable TextView textCode) {
        this.textCode = textCode;
    }

    /**
     * 在activity的onResume里调用
     */
    public void onResume() {
        long sendCodeTime = getSendCodeTime();
        if (sendCodeTime > 0) {
            long lag = new Date().getTime() - sendCodeTime;
            if (lag < 60000) {
                codeTime = (int) ((60000 - lag) / 1000);
                if (codeTime > 0)
                    codeTime();
            }
        }
    }

    /**
     * 在activity的onDestroy里调用
     */
    public void onDestroy() {
        stop = true;
    }

    /**
     * 开始验证码60秒倒计时
     */
    public void start() {
        codeTime = 60;
        setSendCodeTime(new Date().getTime());
        codeTime();
    }

    /**
     * 停止倒计时（无论是否倒计时结束）
     */
    public void stop() {
        setSendCodeTime(0);
        codeTime = 0;
    }

    private TextView textCode;
    private int codeTime;
    private boolean stop = false;
    private int idx;

    public SmsCodeUtils setIdx(int idx) {
        this.idx = idx;
        return this;
    }

    private void codeTime() {
        if (stop) return;
        if (codeTime < 0) {
            //获取验证码
            textCode.setText(R.string.hqyzm);
            textCode.setEnabled(true);
            //editCode.setEnabled(true);
        } else {
            textCode.setText(codeTime + "s");
            textCode.setEnabled(false);
            if (codeTime == 0) textCode.postDelayed(this::codeTime, 100);
            else textCode.postDelayed(this::codeTime, 1000);
        }
        codeTime--;
    }

    /**
     * 设置倒计时的开始时间
     */
    private void setSendCodeTime(long codeTime) {
        if (idx == 0) {
            UserConfig.setSendCodeTime(codeTime);
        } else UserConfig.setSendCodeTime2(codeTime);
    }

    /**
     * 获取上次倒计时开始时间
     */
    private long getSendCodeTime() {
        return idx == 0 ? UserConfig.getSendCodeTime() : UserConfig.getSendCodeTime2();
    }
}
